package app.core;

import app.core.thread.ServiceRunnable;
import app.core.thread.ThreadUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;

/**
 * 服务器
 * @author Guo.Yang
 * @version 1.0
 * @date 2023/1/15 15:27
 */
public class Server {
    /**
     * 成都理工大学工程技术学院 - 学院代码:13668
     */
    private static short port = 13668;
    /**
     * 线程池管理器
     */
    private static ExecutorService executors = ThreadUtil.createExecutorService();
    public static void main(String[] args) {
        ServerSocket serverSocket = startServer(port);
        while (serverSocket != null){
            Socket link = link(serverSocket);
            if (link != null){
                try {
                    executors.execute(new ServiceRunnable(link));
                }catch (RejectedExecutionException reject){
                    System.out.println("拒绝连接:"+ reject.getMessage());
                    try {
                        link.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }catch (Exception e){
                    System.out.println("出现未知异常:"+ e.getMessage());
                }
            }
        }
    }


    /**
     * 等待连接
     * @param socket
     * @return
     */
    public static Socket link(ServerSocket socket){
        try {
            return socket.accept();
        } catch (IOException e) {
            System.out.println("连接异常:"+ e.getMessage());
        }
        return null;
    }

    /**
     * 指定端口号启动服务
     * @param startPort
     * @return
     */
    public static ServerSocket startServer(int startPort){
        try {
            return new ServerSocket(startPort);
        }catch (IOException e){
            System.out.println("启动失败:"+e.getMessage());
            return null;
        }
    }


}
